package com.example.aicloud.controller;

import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aicloud.entity.Answer;
import com.example.aicloud.entity.enums.AiModelEnum;
import com.example.aicloud.entity.enums.AiTypeEnum;
import com.example.aicloud.service.IAnswerService;
import com.example.aicloud.util.AppVariable;
import com.example.aicloud.util.MinioUtil;
import com.example.aicloud.util.ResponseEntity;
import com.example.aicloud.util.SecurityUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import okhttp3.HttpUrl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/xunfei")
public class XunFeiController {
    @Resource
    private IAnswerService answerService;

    @Value("${xunfei.chat.url}")
    private String chatUrl;
    @Value("${xunfei.chat.api-key}")
    private String chatApiKey;
    @Value("${xunfei.chat.api-secret}")
    private String chatApiSecret;
    @Resource
    private ObjectMapper objectMapper;
    @Value("${xunfei.draw.app-id}")
    private String appId;
    @Value("${xunfei.draw.api-key}")
    private String drawApiKey;
    @Value("${xunfei.draw.api-secret}")
    private String drawApiSecret;
    @Value("${xunfei.draw.hostUrl}")
    private String hostUrl;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 聊天功能
     */
    @PostMapping("/chat")
    public ResponseEntity chat(String question) throws JsonProcessingException {
        if (!StringUtils.hasLength(question)){
            // 输入为空
            return ResponseEntity.fail("输入内容不能为空!");
        }
        String content= "";  // 大模型返回结果
        boolean addResult = false; // 数据添加状态
        // 执行分布式锁
        // key
        String lockKey = AppVariable.getModelLockKey(SecurityUtil.getCurrentUser().getUid(), AiModelEnum.XUNFEI.getValue(), AiTypeEnum.CHAT.getValue());
        // 1. 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 2. 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS); //设置最长等待时间30秒
            if (!isLock){
                return ResponseEntity.fail("请勿频繁调用接口！");
            }
            String bodyJson="{\n" +
                    "    \"model\":\"generalv3.5\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \""+ question +"\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            String result=HttpRequest.post(chatUrl)
                    .header("Content-Type","application/json")
                    .header("Authorization","Bearer "+chatApiKey+":"+chatApiSecret)
                    .body(bodyJson)
                    .execute() //执行
                    .body(); //返回结果
            HashMap<String,Object> resultMap = objectMapper.readValue(result,HashMap.class);
            if (!resultMap.get("code").toString().equals("0")){
                return ResponseEntity.fail(resultMap.get("message").toString());
            }
            ArrayList choices =(ArrayList)resultMap.get("choices");
            LinkedHashMap<String,Object> choicesMap= (LinkedHashMap<String,Object>)choices.get(0);
            LinkedHashMap<String,Object> message= (LinkedHashMap<String,Object>)choicesMap.get("message");
            content =  message.get("content").toString();
            // 将结果保存到数据库
            Answer answer=Answer.builder()
                    .title(question)
                    .model(AiModelEnum.XUNFEI.getValue())
                    .type(AiTypeEnum.CHAT.getValue())
                    .uid(SecurityUtil.getCurrentUser().getUid())
                    .content(content)
                    .build();
            addResult = answerService.save(answer);
        }catch (Exception e){

        }finally {
            // 3. 释放分布式锁
            rLock.unlock();
        }

        if (addResult){
            return ResponseEntity.success(content);
        }else {
            return ResponseEntity.fail("数据保存失败，请重试！");
        }

    }

    /**
     * 绘图功能
     */
    @PostMapping("/draw")
    public ResponseEntity draw(String question) throws Exception {
        if (!StringUtils.hasLength(question)){
            // 输入为空
            return ResponseEntity.fail("输入内容不能为空!");
        }
        String imgUrl= "";  // 大模型返回结果
        boolean addResult = false; // 数据添加状态
        // 执行分布式锁
        // key
        String lockKey = AppVariable.getModelLockKey(SecurityUtil.getCurrentUser().getUid(), AiModelEnum.XUNFEI.getValue(), AiTypeEnum.DRAW.getValue());
        // 1. 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 2. 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS); //设置最长等待时间30秒
            if (!isLock){
                return ResponseEntity.fail("请勿频繁调用接口！");
            }
            String url = getAuthUrl(hostUrl,drawApiKey,drawApiSecret);
            String json = "{\n" +
                    "  \"header\": {\n" +
                    "    \"app_id\": \""+appId+"\"\n" +
                    "    },\n" +
                    "  \"parameter\": {\n" +
                    "    \"chat\": {\n" +
                    "      \"domain\": \"general\",\n" +
                    "      \"width\": 512,\n" +
                    "      \"height\": 512\n" +
                    "      }\n" +
                    "    },\n" +
                    "  \"payload\": {\n" +
                    "    \"message\": {\n" +
                    "      \"text\": [\n" +
                    "        {\n" +
                    "          \"role\": \"user\",\n" +
                    "          \"content\": \""+question+"\"\n" +
                    "        }\n" +
                    "      ]\n" +
                    "    }\n" +
                    "  }\n" +
                    "}";
            // 发送请求
            String result = HttpRequest.post(url)
                    .body(json)
                    .execute() //执行
                    .body(); //得到结果
            HashMap<String,Object> resultMap = objectMapper.readValue(result,HashMap.class);
            LinkedHashMap<String,Object> payload= (LinkedHashMap<String,Object>)resultMap.get("payload");
            LinkedHashMap<String,Object> choices= (LinkedHashMap<String,Object>)payload.get("choices");
            ArrayList<LinkedHashMap<String,Object>> text = (ArrayList<LinkedHashMap<String,Object>>)choices.get("text");
            LinkedHashMap<String,Object>  contentMap = text.get(0);
            String content = contentMap.get("content").toString();
            // base64 形式的图片存储在 Minio里
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(content))){
                String imageName = "xf-draw-"+UUID.randomUUID().toString().replace("-","");
                imgUrl = minioUtil.upload(imageName, inputStream, "image/png");
            }
            // 将结果保存到数据库
            Answer answer=Answer.builder()
                    .title(question)
                    .model(AiModelEnum.XUNFEI.getValue())
                    .type(AiTypeEnum.DRAW.getValue())
                    .uid(SecurityUtil.getCurrentUser().getUid())
                    .content(imgUrl)
                    .build();
            addResult = answerService.save(answer);
        }catch (Exception e){

        }finally {
            rLock.unlock();
        }

        if (addResult){
            return ResponseEntity.success(imgUrl);
        }else {
            return ResponseEntity.fail("数据保存失败，请重试！");
        }
    }


    // 鉴权方法
    /**
     * 讯飞大模型URL 签名方法
     */
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }
    /**
     * 获取 XunFei 聊天历史信息
     */
    @PostMapping("/getchatlist")
    private ResponseEntity getChatList(){
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type= AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.XUNFEI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid,model , type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        //缓存中没有数据，从数据库中查询
        if (list == null){
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",uid);
            queryWrapper.eq("type",type);
            queryWrapper.eq("model",model);
            queryWrapper.orderByDesc("aid"); //createtime也可以，但aid是主键，聚簇索引查询效率高
            List<Answer> dataList=answerService.list(queryWrapper);
            // 存储到缓存中
            redisTemplate.opsForValue().set(cacheKey,dataList,1, TimeUnit.DAYS);
            return ResponseEntity.success(dataList);
        }else {
            return ResponseEntity.success(list);
        }

    }

    /**
     * 获取 XUNFei 绘图历史信息
     */
    @PostMapping("/getdrawlist")
    private ResponseEntity getDrawList(){
        Long uid =SecurityUtil.getCurrentUser().getUid();
        int type= AiTypeEnum.DRAW.getValue();
        int model = AiModelEnum.XUNFEI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid,model , type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null){
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",uid);
            queryWrapper.eq("type",type);
            queryWrapper.eq("model",model);
            queryWrapper.orderByDesc("aid"); //createtime也可以，但aid是主键，聚簇索引查询效率高
            List<Answer> dataList=answerService.list(queryWrapper);
            // 存储到缓存中
            redisTemplate.opsForValue().set(cacheKey,dataList,1, TimeUnit.DAYS);
            return ResponseEntity.success(dataList);
        }else {
            return ResponseEntity.success(list);
        }
    }
}
